#include <windows.h>
#include <vector>
#include <assert.h>
#include <cctype>
#include "DlgEntry.h"

using namespace std;

#define OK_ID 1019
#define CANCEL_ID 1020

extern vector<DlgEntry*> entrys;
extern HINSTANCE _hInst ;  // this instance is defined in DIVA_MAIN
extern int x,y,width,height;
extern int button_space;

const int MAX_ENTRY = 64;


HWND hctrl[MAX_ENTRY];
HWND hbtn[2];//OK,CANCEL
bool bCancel_dyn;

void initial_entry(HWND hDlg){
	vector<DlgEntry*>::iterator itor;
	int i;

	for(itor = entrys.begin(), i=0;itor!=entrys.end();itor++,i++){
		DlgEntry* entry = (*itor);
		/*TODO: change to Qt window*/
		//hctrl[i] = CreateWindow(entry->type,entry->default_val, entry->style,
		//	entry->x, entry->y,
		//	entry->width, entry->height,
		//	hDlg,(HMENU)entry->id,_hInst,NULL
		//	);
	}
	/*TODO: change to Qt window*/
	//hbtn[0] = CreateWindow("BUTTON", "OK", WS_CHILD|WS_VISIBLE,
		//width/10, height,
		//width/3, button_space/3,
		//hDlg,(HMENU)OK_ID,_hInst,NULL
		//);
	//hbtn[1] = CreateWindow("BUTTON", "CANCEL", WS_CHILD|WS_VISIBLE,
	//	(width*57)/100, height,
	//	width/3, button_space/3,
	//	hDlg,(HMENU)CANCEL_ID,_hInst,NULL
	//	);

}

bool isNum(string s){
	for(int i=0;i<s.size();i++){
		if(!isdigit(s[i]))
			return false;
	}
	return true;
}

void dynamic_buttonManage(WPARAM wParam, HWND hDlg){
	switch (LOWORD(wParam)) {
		case CANCEL_ID:
			bCancel_dyn = true;
			EndDialog(hDlg, TRUE);

		case OK_ID:
			vector<DlgEntry*>::iterator itor;
			for(itor = entrys.begin();itor!=entrys.end();itor++){
				DlgEntry* entry = (*itor);
				int len;
				len = GetWindowTextLength(GetDlgItem(hDlg, entry->id));
				if(len > 0){
					char* buf;
					buf = (char*)GlobalAlloc(GPTR, len + 1);
					GetDlgItemText(hDlg, entry->id, buf, len + 1);
					entry->value = buf;
					GlobalFree((HANDLE)buf);

					if((entry->valueType).compare("int")==0&&isNum(entry->value)==false)
						assert(false);
					//錯誤的輸入
				}
			}

			EndDialog(hDlg, TRUE);
	}
}

BOOL CALLBACK DynDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam){
	switch (message) {
		case WM_INITDIALOG:
			bCancel_dyn = false;
			SetWindowPos(hDlg, NULL,x,y,width,height+button_space,NULL);
			initial_entry(hDlg);
			UpdateWindow(hDlg);
			break;
		case WM_PAINT:
			break;

		case WM_COMMAND:
			dynamic_buttonManage(wParam, hDlg);	
			return (TRUE);

		case WM_DRAWITEM:
			return (TRUE);
	}
	return (FALSE); 

}